package com.ohuang.wallpapermanager.screen

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.ohuang.wallpapermanager.compose.SpinnerDropdown
import com.ohuang.wallpapermanager.compose.TipDialog
import com.ohuang.wallpapermanager.compose.clickableSafe
import com.ohuang.wallpapermanager.compose.dp2sp
import com.ohuang.wallpapermanager.config.LogConfig
import com.ohuang.wallpapermanager.vm.SettingViewModel

data class SettingScreenState(
    val isLoading: Boolean = false,
    val categoryEnable: Boolean = true,
    val lastUpdateTime: String = "12:12",
    val isUseWallPaperService: Boolean = true,
    val wallPaperServiceShowMode: Int = 0,
    val lockWallPaper: SettingScreenWallPaperState = SettingScreenWallPaperState(),
    val homeWallPaper: SettingScreenWallPaperState = SettingScreenWallPaperState()
)

data class SettingScreenWallPaperState(
    val categoryEnable: Boolean = true,
    val randomInterval: String = "无间隔",
    val lastUpdateTime: String = "12:12"
)

sealed class SettingScreenStateEvent {
    class CategoryEnable(val enable: Boolean) : SettingScreenStateEvent()

    class WallPaperServiceShowMode(val mode: Int) : SettingScreenStateEvent()
    class UseWallPaperService(val isUse: Boolean) : SettingScreenStateEvent()
    class SynchronizationWallWallPaper(val isForced: Boolean) : SettingScreenStateEvent()
    class WallPaperRandomInterval(val isLock: Boolean, val interval: Long) :
        SettingScreenStateEvent()

    class WallPaperCategoryEnable(val isLock: Boolean, val enable: Boolean) :
        SettingScreenStateEvent()
}


@Composable
fun SettingScreen(
    goBack: () -> Unit,
    viewModel: SettingViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
) {

    LaunchedEffect(key1 = Unit, block = {
        viewModel.init()
    })
    Column {
        TopBar(title = "设置", backClick = goBack)
        SettingScreenImpl(state = viewModel.settingScreenState.value, onEvent = {
            viewModel.onEvent(it)
        })
        if (viewModel.settingScreenState.value.isLoading) {
            Dialog(
                onDismissRequest = { },
                properties = DialogProperties(
                    dismissOnBackPress = true,
                    dismissOnClickOutside = false
                )
            ) {
                Box(modifier = Modifier.fillMaxSize()) {


                    Box(
                        modifier = Modifier
                            .align(Alignment.Center)
                            .width(200.dp)
                            .height(300.dp)
                            .background(Color.White, shape = RoundedCornerShape(10.dp))
                    ) {
                        Column(
                            modifier = Modifier.align(Alignment.Center),
                            verticalArrangement = Arrangement.Center,
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            CircularProgressIndicator()
                            Text("加载中...", modifier = Modifier.padding(top = 20.dp))
                        }
                    }
                }
            }
        }
    }
}

@Preview(backgroundColor = 0xffffffff, showBackground = true)
@Composable
private fun SettingScreenImplShow() {
    SettingScreenImpl(state = SettingScreenState(), onEvent = {})
}

@Composable
private fun SettingScreenImpl(
    state: SettingScreenState,
    onEvent: (SettingScreenStateEvent) -> Unit
) {
    Column(
        modifier = Modifier
            .verticalScroll(rememberScrollState())
            .padding(15.dp)
    ) {
        HomeActionItemComposable(title = "同步壁纸") {
            onEvent(SettingScreenStateEvent.SynchronizationWallWallPaper(false))
        }
        HomeActionItemComposable(title = "强制同步壁纸") {
            onEvent(SettingScreenStateEvent.SynchronizationWallWallPaper(true))
        }

        LastRunTime(state)

        SettingWitchComposable(
            title = "定时壁纸总开关", isOpen = state.categoryEnable,
            onOpenChange = { onEvent(SettingScreenStateEvent.CategoryEnable(it)) }
        )
        AnimatedVisibility(visible = state.categoryEnable) {
            Column {
                SettingWitchComposable(
                    title = "是否通过动态壁纸服务实现切换壁纸",
                    isOpen = state.isUseWallPaperService,
                    onOpenChange = { onEvent(SettingScreenStateEvent.UseWallPaperService(it)) }
                )
                WallPaperShowModeScreen(state.wallPaperServiceShowMode, onEvent = onEvent)
                SettingWallPaperComposable(
                    "锁屏", isLock = true, state = state.lockWallPaper,
                    onEvent = onEvent
                )

                SettingWallPaperComposable(
                    "桌面", isLock = false, state = state.homeWallPaper,
                    onEvent = onEvent
                )
            }
        }

    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun WallPaperShowModeScreen(modeValue: Int, onEvent: (SettingScreenStateEvent) -> Unit) {

    Column {
        HomeActionItemComposable(title = "动态壁纸跟随模式:") {

        }
        val modes = arrayOf("独自显示", "跟随锁屏", "跟随桌面")
        FlowRow {
            modes.forEachIndexed() { index, s ->
                val isSelect = modeValue == index
                SelectText(
                    modifier = Modifier
                        .width(100.dp)
                        .height(50.dp)
                        .padding(10.dp)
                        .clickableSafe {
                            onEvent(SettingScreenStateEvent.WallPaperServiceShowMode(index))
                        }, text = s, isSelect = isSelect
                )
            }
        }
    }

}

@Composable
private fun LastRunTime(state: SettingScreenState) {
    val isShowDialog = remember {
        mutableStateOf(false)
    }
    HomeActionItemComposable(title = "上次执行时间:${state.lastUpdateTime}") {
        isShowDialog.value = true
    }
    LogDialog(isShowDialog)
}

@Composable
private fun LogDialog(state: MutableState<Boolean>) {
    val logMsg = remember {
        mutableStateOf("")
    }

    LaunchedEffect(key1 = state.value, block = {
        logMsg.value = LogConfig.getLog().ifEmpty {
            "没有日志"
        }
    })

    if (state.value && logMsg.value.isNotEmpty()) {
        TipDialog(
            title = "日志",
            content = logMsg.value,
            btnString = "清除",
            confirmClick = {
                LogConfig.clearAllLog()
                state.value = false
            },
            onDismissRequest = {
                state.value = false
            })
    }
}

@Composable
private fun SettingWallPaperComposable(
    title: String,
    isLock: Boolean,
    state: SettingScreenWallPaperState,
    onEvent: (SettingScreenStateEvent) -> Unit
) {
    Column() {
        SettingWitchComposable(
            title = "${title}壁纸开关",
            isOpen = state.categoryEnable,
            onOpenChange = {
                onEvent(
                    SettingScreenStateEvent.WallPaperCategoryEnable(
                        isLock = isLock,
                        enable = it
                    )
                )
            })
        val mapOf = mapOf(
            "15分钟" to 15L * 60_000L,
            "30分钟" to 30L * 60_000L,
            "1小时" to 3600_000L,
            "2小时" to 2L * 3600_000L,
            "4小时" to 4L* 3600_000L,
            "8小时" to 8L * 3600_000L,
            "12小时" to 12L * 3600_000L,
            "24小时" to 24L * 3600_000L,
            "48小时" to 48L * 3600_000L,
            "72小时" to 72L * 3600_000L,
            "一周" to 7L * 24L * 3600_000L
        )

        AnimatedVisibility(visible = state.categoryEnable) {
            Column {
                SpinnerDropdown(items = mapOf.keys.toList(),
                    onItemSelected = { index, it ->
                        val time = mapOf[it]!!
                        onEvent(SettingScreenStateEvent.WallPaperRandomInterval(isLock, time))
                    }) {
                    TextItemComposable("${title}壁纸更新间隔(强制显示的不受时间间隔的限制):" + state.randomInterval)
                }
                HomeActionItemComposable(title = title + "壁纸最近更新时间:" + state.lastUpdateTime) {
                }
            }
        }


    }
}

@Composable
private fun SettingWitchComposable(
    title: String, isOpen: Boolean, onOpenChange: (Boolean) -> Unit
) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Switch(
            checked = isOpen, onCheckedChange = onOpenChange
        )
        Text(modifier = Modifier.padding(start = 10.dp), text = title)

    }

}

@Composable
private fun TextItemComposable(title: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(50.dp)
    ) {
        Text(
            modifier = Modifier.align(Alignment.CenterVertically),
            text = title,
            fontSize = 16.dp2sp()
        )
    }
}

